package cc.ug_project.rollcall.Bussness

import cc.ug_project.rollcall.Bussness.DataModel.User
import cc.ug_project.rollcall.Bussness.DataProviders.UserDataProvider
import cc.ug_project.rollcall.Core.Observer.observable
import cc.ug_project.rollcall.Core.ViewModel.IViewModel

/**
 * Created by yeganaaa on 4/3/18.
 */
enum class UserSignInState {
    NotStarted,
    SigningIn
}
class UserViewModel(val provider: UserDataProvider) : IViewModel {
    val canSignInDelegate = observable(false)
    val nameDelegate = observable("")
    val pwdDelegate = observable("")
    val exceptionDelegate = observable(Exception())
    val userDelegate = observable(User())
    val notFoundDelegate = observable(false)
    val signInStateDelegate = observable(UserSignInState.NotStarted)

    var name by nameDelegate
    var password by pwdDelegate
    var canSignIn by canSignInDelegate
    var exception by exceptionDelegate
    var user by userDelegate
    var notFoundUser by notFoundDelegate
    var userSignInState by signInStateDelegate

    init {
        nameDelegate.apply { innerSet = { checkCanSignInState() } }
        pwdDelegate.apply { innerSet = { checkCanSignInState() } }
    }

    private fun checkCanSignInState() {
        canSignIn = name.length > 10 && password.length > 5
    }

    fun signIn() {
        userSignInState = UserSignInState.SigningIn
        try {

            provider.SignIn(name, password) { data, exception ->
                if (exception == null)
                    if (data != null)
                        this.user = data
                    else
                        notFoundUser = true
                else
                    this.exception = exception
                userSignInState = UserSignInState.NotStarted
            }
        }
        catch (exception: Exception){
            exception.printStackTrace()
        }
    }
}
